import { View, Text, Image, Textarea } from "@tarojs/components";
import Taro, { useLoad } from "@tarojs/taro";
import { Button, Cell, CellGroup, Dialog, Empty, NavBar, Picker } from "@nutui/nutui-react-taro";
import { c } from "../../../common/index.js";
import { useEffect, useState } from "react";
import SelectItem from "../../../components/selectItem/index.jsx";
import InputItem from "../../../components/inputItem/index.jsx";
import dayjs from "dayjs";
import { getStore } from "../../../utils/localStore.js";
import { addApply } from "../../../api/apply.js";
import { baseUrl, uploadFile } from "../../../utils/request.js";
import { iconAdd } from "../../../assets/files.js";
import { hiddenDangerInfoAdd } from "../../../api/yinhuan.js";
import "./index.scss";

export default function Apply(props) {

  const [isVisible4, setIsVisible4] = useState(false)
  const [imgList, setImgList] = useState([]);

  const [location, setLocation] = useState('')
  const [address, setAddress] = useState('')
  const [jurisdiction, setJurisdiction] = useState('')
  
  const [trainingTime, setTrainingTime] = useState('')
  const [phone, setPhone] = useState(getStore("userInfo").loginCode)
  const [content, setContent] = useState("")

  const submit = async () => {

    const errorMessage = verify();
    console.log(errorMessage);
    if (errorMessage) {
      Taro.showToast({
        icon: "none",
        title: errorMessage,
      });
      return;
    }

    console.log(dayjs().format('YYYY-'));

    let list = []
    imgList.forEach(v => {
      list.push({
        sysFileId: v,
        sysFileUrl: v
      })
    })

    const params = {
      jurisdiction,
      location:address+location,
      phone,
      content,
      list
    }

    const { success, msg } = await hiddenDangerInfoAdd(params)
    if (success) {
      Taro.showModal({
        title: '提交成功，感谢您对消防工作的关注和参与！',
        showCancel: false,
        complete(res) {
          if (res.confirm) {
            Taro.navigateBack()
          }
        }
      })

    } else {
      setIsVisible4(false)
      Taro.showModal({
        content: msg
      })
    }
  }

  function verify() {
    if (!content) return "请输入隐患内容";
    if (!location) return "请选择隐患位置";
    if (imgList.length === 0) return "请上传隐患图片";
  }

  function selectImg() {
    Taro.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: async function (res) {
        // 选择成功时返回的临时文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        //  const tempFilePaths = res.tempFilePaths?.[0];
        // console.log(tempFilePaths1);

        const tempFilePaths = res.tempFilePaths?.[0];
        console.log(tempFilePaths); // 这里可以获取到图片的临时路径
        Taro.showLoading({
          title: "上传中...",
        });
        // const { data, success, msg } = await uploadFileList("xiaofangPeixun", tempFilePaths.toString());
        const { data, success, msg } = await uploadFile("xiaofangPeixun", tempFilePaths);
        setImgList([...imgList, data.fileUrl])
        // updateUser({ headId: data.fileUrl }).then(rs=>{
        //   getUserInfo()
        // })

        Taro.hideLoading();
        if (!success) {
          Taro.showToast({
            title: msg,
            icon: "none",
          });
          return;
        }

      }
    });
  }

  const delImg = (index) => {
    let arr = JSON.stringify(imgList)
    arr = JSON.parse(arr)
    arr.splice(index, 1)
    setImgList(arr)
  }

  async function getAddressInfo(longitude, latitude, codeMobile) {
    const { data } = await Taro.request({
      url: "https://restapi.amap.com/v3/geocode/regeo",
      method: 'get',
      data: {
        key: "677d1e9aa3b338a8b35c9498790f1bf8",
        location: longitude + "," + latitude,
      }
    })

    if (data.info === 'OK') {
      const { province, city, district } = data?.regeocode?.addressComponent
      setJurisdiction(province+city+district)
      // register({ codeMobile, province, city, districts:district }).then(res => {
      //   loginSuccessCallback(res)
      // })
    } else {
      // Taro.showToast({ title: '获取位置信息失败' })
    }
  }

  function registerFn() {
    Taro.getLocation({
      success(res) {
        Taro.chooseLocation({
          latitude: res.latitude,
          longitude: res.longitude,
          success: (res) => {

            setLocation(res.name)
            setAddress(res?.address)
            console.log(res);
            getAddressInfo( res.longitude,res.latitude)
            
          }
        })
      },
      fail(err){
        Taro.chooseLocation({
          latitude:"24.341098",
          longitude: "102.540179",
          success: (res) => {
            setLocation(res.name)
            setAddress(res?.address)
            console.log(res);
          }
        })
      }
    })
  }

  return (
    <View className="wrap">

      <View className="formWrap">

        <SelectItem
          label={"隐患位置"}
          value={location}
          labelClass="imgTitle"
          placeholder="请选择隐患位置"
          required
          style={{ borderTopLeftRadius: 16, borderTopRightRadius: 16, }}
          onclick={() => registerFn()}
        />
        <InputItem
          disabled
          label={"联系电话"}
          value={phone}
          required
          labelClass="imgTitle"
          onChange={(val) => {
            setPhone(val)
          }}
        />
        <View className="formtipWrap">
          <Text className="formtip">注：为了便于我们为您提供更加完善的服务，请确保您的电话保持畅通</Text>
        </View>
      </View>

      <View className="formWrap">

        <View className="remarkWrap">
          <Text className="imgTitle">
            <Text className="xing">*</Text>
            隐患内容</Text>
          <Textarea maxlength={200} className="remarkSty" placeholder="请输入隐患内容" onInput={(val) => {
            if(val.detail.value.length>=201) return
            setContent(val.detail.value)
          }} />
          <Text className="limitReamrk">（{content.length}/200）</Text>
        </View>

        <View className="overWrap">
          <View className="zpWrap">
            <Text className="imgTitle">
              <Text className="xing">*</Text>
              隐患照片
            </Text>
            <Text className="limit">{imgList.length}/6</Text>
          </View>
          <View className="sImgWrap">
            {
              imgList.map((v, i) => {
                return (
                  <View className="uploadItem">
                    <Image src={baseUrl + v} className="sImg" />
                    <View className="iconCloseSty" onClick={() => delImg(i)}>
                      {/* <Text className="chacha">✖</Text> */}
                      <Text className="chacha">删除</Text>
                    </View>
                  </View>
                )
              })
            }
            {
              imgList.length < 6 &&
              <View className="uploadDefault" onClick={selectImg}>
                <Image src={iconAdd} className="iconAdd" />
                <Text className="upText">上传照片</Text>
              </View>
            }
          </View>

        </View>

      </View>

      <View className="bottomBtnWrap">
        <Button onclick={() => submit()} className="addBtn" size="large" block type="primary" color="#6486FF"> 提交 </Button>
      </View>
    </View>
  );
}
